<template>
  <div class="row" id="queryactually">
    <div class="col-sm-9">
      <criteria-paged :model="model" v-ref:paged  @condition-changed="selfSearch">
    		<criteria partial='criteria' v-ref:criteria>
    	  	<div novalidate class="form-horizontal select-overspread" partial>
            <div calss= "row">
            <div class="col-sm-3 form-group form-input-group">
              <label class="control-label">用户编号</label>
              <input  type="text" class="form-control" v-model="model.f_userinfo_id"
              condition="all_用户编号_1 = '{}' " placeholder="用户编号"
              :size="model.f_userinfo_id ? model.f_userinfo_id.length : 1">
            </div>
            <div class="col-sm-3 form-group form-input-group">
              <label class="control-label">用户姓名</label>
              <input  type="text" class="form-control" v-model="model.f_user_name"
              condition="all_用户姓名_2 like '%{}%'" placeholder="用户姓名"
              :size="model.f_user_name ? model.f_user_name.length : 1">
            </div>
            <div class="col-sm-3 form-group form-input-group">
              <label class="control-label">用户电话</label>
              <input  type="text" class="form-control" v-model="model.f_user_phone"
              condition="all_用户电话_41 like '%{}%'" placeholder="用户电话"
              :size="model.f_user_phone ? model.f_user_phone.length : 1">
            </div>
            <div class="col-sm-3 form-group form-input-group">
              <label class="control-label">身份证号</label>
              <input type="text" class="form-control" v-model="model.f_idnumber"
              condition="all_身份证号_42 like '%{}%'" placeholder="身份证号"
              :size="model.f_idnumber ? model.f_idnumber.length * 2 : 1">
            </div>
            <div class="form-group" v-show="!$parent.$parent.bussiness" style="margin-bottom: 0px;">
              <div class="col-sm-3 form-group form-input-group">
                <label class="control-label">区/县</label>
                <v-select
                  :value.sync="model.f_area"
                  v-model="model.f_area"
                  :options='$parent.$parent.areas'
                  placeholder='请选择'
                  condition="all_区县_61 = '{}'"
                  @change='$parent.$parent.areachange'
                  close-on-select></v-select>
              </div>
              <div class="col-sm-3 form-group form-input-group">
                <label class="control-label">片区</label>
                <v-select
                  :value.sync="model.f_slice_area"
                  v-model="model.f_slice_area"
                  :options='$parent.$parent.slices'
                  placeholder='请选择'
                  condition="all_片区管理站_62 = '{}'"
                  close-on-select></v-select>
              </div>
              <div class="col-sm-3 form-group form-input-group">
                <label class="control-label">调压箱</label>
                <v-select
                  :value.sync="model.f_adjustable_name"
                  v-model="model.f_adjustable_name"
                  :options='$parent.$parent.adjustables'
                  placeholder='请选择'
                  condition="all_调压箱名称_63 = '{}'"
                  :search='true'
                  close-on-select></v-select>
              </div>
              <div class="col-sm-3 form-group form-input-group">
                <label for="" class="control-label">小区</label>
                <input type="text" class="form-control" v-model="model.f_residential_area"
                condition="all_小区_64 like '%{}%'" placeholder="小区"
                close-on-select/>
              </div>
            </div>
            <!-- <div class="col-sm-3 form-group form-input-group">
              <label class="control-label">气表类型</label>
              <v-select :value.sync="model.f_meter_type"
                  :options='$parent.$parent.metertypes' placeholder='请选择' v-model="model.f_meter_type"
                  condition="u.f_meter_type = '{}'"
                  close-on-select></v-select>
            </div> -->
            <div class="col-sm-3 form-group form-input-group">
              <label class="control-label">用户地址</label>
              <input  type="text" class="form-control" v-model="model.f_address"
              condition="all_用户地址_43 like '%{}%'" placeholder='用户地址'
              :size="model.f_address ? model.f_address.length * 2 : 1">
            </div>
            <div class="col-sm-3 form-group form-input-group">
              <label class="control-label">用户类型</label>
              <v-select :value.sync="model.f_user_type"
                  :options='$parent.$parent.usertypes' placeholder='请选择' v-model="model.f_user_type"
                  condition="all_用户类型_44 = '{}'"
                  close-on-select></v-select>
            </div>
            <div class="col-sm-3 form-group form-input-group">
              <label class="control-label">用气性质</label>
              <v-select :value.sync="model.f_gasproperties" v-model="model.f_gasproperties"
                  :options='$parent.$parent.gasproperties' placeholder='请选择'
                  condition="all_用气性质_45 = '{}'"
                  close-on-select></v-select>
            </div>
            <div class="col-sm-3 form-group form-input-group" v-show="!$parent.$parent.bussiness">
              <label class="control-label">用户状态</label>
              <v-select :value.sync="model.f_user_state"
                  v-model="model.f_user_state"
                  :options='$parent.$parent.userstates' placeholder='请选择'
                  condition="all_状态_24 = '{}'"
                  close-on-select></v-select>
            </div>

            <!-- 业务组件 -->
            <div class="form-group" v-show="$parent.$parent.bussiness" style="margin-bottom: 0px;">
              <div class="col-sm-3 form-group form-input-group">
                <label class="control-label">表编号</label>
                <input  type="text" class="form-control" v-model="model.f_user_id"
                condition="all_表编号_61 = '{}'" placeholder='表编号'
                :size="model.f_user_id ? model.f_user_id.length : 1">
              </div>
              <!-- <div class="col-sm-3 form-group form-input-group">
                <label class="control-label">气价名称</label>
                <input  type="text" class="form-control" v-model="model.f_price_name"
                condition="u.f_price_name = '{}'" placeholder='气价名称'
                :size="model.f_price_name ? model.f_price_name.length : 1">
              </div> -->
              <div class="col-sm-3 form-group form-input-group">
                <label class="control-label">气表分类</label>
                <v-select :value.sync="model.f_meter_classify"
                    v-model="model.f_meter_classify"
                    :options='$parent.$parent.metertypes' placeholder='请选择'
                    condition="all_气表分类_62 = '{}'"
                    close-on-select></v-select>
              </div>
              <div class="col-sm-3 form-group form-input-group">
                <label class="control-label">气表品牌</label>
                <v-select :value.sync="model.f_meter_brand"
                    v-model="model.f_meter_brand"
                    :options='$parent.$parent.meterbrands' placeholder='请选择'
                    condition="all_气表品牌_63 = '{}'"
                    close-on-select></v-select>
              </div>


              <div class="col-sm-3 form-group form-input-group">
                <label class="control-label">卡号</label>
                <input  type="text" class="form-control" v-model="model.f_card_id"
                condition="all_卡号_64 like '%{}%'" placeholder='卡号'
                :size="model.f_card_id ? model.f_card_id.length : 1">
              </div>
              <div class="col-sm-3 form-group form-input-group" >
                <label class="control-label">状态</label>
                <v-select :value.sync="model.f_state"
                    v-model="model.f_state"
                    :options='$parent.$parent.states' placeholder='请选择'
                    condition="all_状态_24 = '{}'"
                    close-on-select></v-select>
              </div>
            </div>



            <!-- <div class="col-sm-3 form-group form-input-group">
              <label for="operatordate" class="control-label">操作日期</label>
              <datepicker id="operatordate" placeholder="操作日期" width='100%'
                v-model="model.startDate"
                :value.sync="model.startDate"
                :disabled-days-of-Week="[]"
                :format="'yyyy-MM-dd'"
                condition="all_操作时间_22 = {}"
                :show-reset-button="reset">
              </datepicker>
            </div> -->
            <div class="col-sm-3 form-group form-input-group">
              <label for="startDate" class="control-label">开始日期</label>
              <datepicker id="startDate" placeholder="开始日期" width='100%'
                v-model="model.startDate"
                :value.sync="model.startDate"
                :format="'yyyy-MM-dd'"
                condition="all_操作时间_23 >= '{} 00:00:00'"
                :show-reset-button="true">
              </datepicker>
            </div>

            <div class="col-sm-3 form-group form-input-group">
              <label for="endDate" class="control-label">结束日期</label>
              <datepicker id="endDate" placeholder="结束日期" width='100%'
                v-model="model.endDate"
                :value.sync="model.endDate"
                :format="'yyyy-MM-dd'"
                condition="all_操作时间_23 <= '{} 23:59:59'"
                :show-reset-button="true">
              </datepicker>
            </div>
            <div class="col-sm-3 form-group form-input-group">
              <label for="" class="control-label">营业网点</label>
                <v-select id="f_outlets"
                v-model="model.f_outlets"
                placeholder='请选择'
                condition="all_营业厅_21 ='{}'"
                :value.sync="model.f_outlets"
                :options='$parent.$parent.outlets'
                @change='$parent.$parent.outletsChange'
                close-on-select clear-button>
                </v-select>
            </div>
            <div class="col-sm-3 form-group form-input-group">
              <label for="" class="control-label">操作员</label>
              <v-select id="f_operator"
              v-model="model.f_operator"
              placeholder='请选择'
              condition="all_操作人员_22 ='{}'"
              :value.sync="model.f_operator"
              :options='$parent.$parent.operators'
              close-on-select clear-button>
              </v-select>
            </div>

            </div>
            <div class="span" style = "float:right;margin-top:10px">
                <button class="btn btn-success  width-100" @click="search()">查询</button>
                <!-- <button class="btn btn-success  width-100" @click="search()">打印</button>
                <button class="btn btn-success  width-100" @click="search()">导出Excel</button> -->
                <button class="btn btn-success  width-100" @click="$parent.$parent.clear()">清空</button>
                <export-excel :data="$parent.$parent.getCondition" :field="$parent.$parent.getField" :template-name="$parent.$parent.$parent.types[0].type.trim()" sqlurl="rs/logic/exportfile" :bean="$parent.$parent.$parent.types[0].type.trim()"></export-excel>
            </div>
    	  	</div>
    	 	</criteria>
    		<data-grid :model="model" partial='list' v-ref:grid id="test" >
    	  	<template partial='head'>
    			<tr>
    				<th v-for="item in $parent.$parent.$parent.thObj"><nobr>{{item.split('_')[1]}}</nobr></th>
    			</tr>
    		  </template>
    		  <template partial='body' >
    				<td v-for="item in $parent.$parent.$parent.thObj"><nobr>{{row[item]}}</nobr></td>
    		  </template>
    	  </data-grid>
       </criteria-paged>
    </div>
    <div class="col-sm-3 select-overspread flex" style="padding-left: 15px;">
      <div>
        <h3 class="text-center" style="margin-top: 0px;">分类查询条件</h3>
        <sell-condition v-show="include('sell-condition')" v-ref:sell></sell-condition>
        <hand-condition v-show="include('hand-condition')" v-ref:hand></hand-condition>
        <changemeter-condition v-show="include('changemeter-condition')" v-ref:changemeter></changemeter-condition>
        <tran-condition v-show="include('tran-condition')" v-ref:tran></tran-condition>
        <other-condition v-show="include('other-condition')" v-ref:other></other-condition>
        <pay-condition v-show="include('pay-condition')" v-ref:pay></pay-condition>
        <correct-condition v-show="include('correct-condition')" v-ref:correct></correct-condition>
        <fillcard-condition v-show="include('fillcard-condition')" v-ref:fillcard></fillcard-condition>
        <fillgas-condition v-show="include('fillgas-condition')" v-ref:fillgas></fillgas-condition>
        <operator-condition v-show="include('operator-condition')" v-ref:oper></operator-condition>
        <cancel-condition v-show="include('cancel-condition')" v-ref:cancel></cancel-condition>
        <userfiles-condition v-show="include('userfiles-condition')" v-ref:meter></userfiles-condition>
        <userinfo-condition v-show="include('userinfo-condition')" v-ref:info></userinfo-condition>
        <device-condition v-show="include('device-condition')" v-ref:device></device-condition>
      </div>

      <div style="max-height: 300px;">
        <sum-view :data='model' v-show="include('-condition')"></sum-view>
      </div>
    </div>
    <!-- <div class="col-sm-3" style="padding-left: 15px;">

    </div> -->
  </div>
</template>

<script>
import { PagedList } from 'vue-client'
import AppData from '../../../../stores/AppData'
import * as Util from '../../../Util'
import co from 'co'
import allData from './left/config'
import fileData from './left/fileconfig'
import queryData from './export/exportConfig'

let paramletGen = function * (self) {
  let outlets = yield self.$post('/rs/search', {source: 'tool.getChildrenOfResName($晋城市煤气开发利用中心$)', userid: ''}, {resolveMsg: null, rejectMsg: null})
  let getAreas = yield self.$post('/rs/search', {source: 'tool.getChildrenOfResName($区$)', userid: ''}, {resolveMsg: null, rejectMsg: null})

  outlets.data.forEach((item, next) => {
    let temp = {}
    temp.label = item.name
    temp.value = item.name
    self.outlets.push(temp)
  })

  getAreas.data.forEach((item, next) => {
    let temp = {}
    temp.label = item.name
    temp.value = item.name
    self.areas.push(temp)
  })
  self.outlets = [{label: '全部', value: ''}, ...self.outlets]
  self.areas = [{label: '全部', value: ''}, ...self.areas]
  console.log('获取参数', self.outlets, self.areas)
}

let sliceletGen = function * (self, val) {
  let getSlices = yield self.$post('/rs/search', {source: `tool.getChildrenOfResName($${val}$)`, userid: ''}, {resolveMsg: null, rejectMsg: null})
  getSlices.data.forEach((item, next) => {
    let temp = {}
    temp.label = item.name
    temp.value = item.name
    self.slices.push(temp)
  })
  self.slices = [{label: '全部', value: ''}, ...self.slices]
}

let operatorletGen = function * (self, val) {
  let getOperators = yield self.$post('/rs/search', {source: `tool.getChildrenOfResName($${val}$)`, userid: ''}, {resolveMsg: null, rejectMsg: null})
  getOperators.data.forEach((item, next) => {
    let temp = {}
    temp.label = item.name
    temp.value = item.name
    self.operators.push(temp)
  })
  self.operators = [{label: '全部', value: ''}, ...self.operators]
}

export default {
  title: '综合查询',
  data () {
    return {
      model: new PagedList('rs/sql/sellQuery', 20, {}, {all_气量_11: 0, all_应交金额_12: 0, all_收款_13: 0}),
      allTypes: allData.allData,
      fileTypes: fileData.allData,
      queryDatas: queryData.allData,
      heardStr: ['all'],
      thObj: [],
      bussiness: true,
      outlets: [],
      areas: [],
      slices: [],
      operators: []
    }
  },
  ready () {
    this.getParams()
    this.$refs.paged.$refs.criteria.model.startDate = Util.toStandardDateString()
    this.$refs.paged.$refs.criteria.model.endDate = Util.toStandardDateString()
    this.$refs.paged.$refs.criteria.search()
  },
  props: {
    types: {
      type: Array,
      default: function () {
        return []
      }
    },
    typename: {
      type: String
    }
  },
  methods: {
    include (component) {
      for (var i = 0; i < this.types.length; i++) {
        if (this.types[i].component.includes(component)) {
          return true
        }
      }
      return false
    },
    selfSearch (args) {
      this.heardStr = ['all']
      let distinct = [['all']]
      this.allTypes.forEach((item) => {
        this.model.paramSource[item.condition] = `"${args.condition}"` // 先将所有条件设为false
      })
      this.fileTypes.forEach((item) => {
        this.model.paramSource[item.condition] = `"${args.condition}"` // 先将所有条件设为false
      })
      // console.log('123111111777777', args.condition)
      if (this.types.length === 0) { // 所有condition传入公共提交,显示字段为固定字段
        this.allTypes.forEach((item) => {
          this.model.paramSource[item.condition] = `"${args.condition}"`
        })
        this.fileTypes.forEach((item) => {
          this.model.paramSource[item.condition] = `"${args.condition}"`
        })
      } else { // 选中那个，那个传入那个condition和公共condition提交，其余condition传入'1<>1'
        this.types.forEach((item) => {
          // console.log('123111111', this.$refs[item.ref], item.ref)
          this.model.paramSource[item.condition] = `"${args.condition} ${this.$refs[item.ref].getArgs().condition.replace('1=1', '')}"`
          distinct = this.fliterArr(distinct, item.heardStr)
          this.heardStr = this.together(distinct)
        })
      }
      this.model.search('1=1', this.model)
    },
    // 过滤出要筛选的列
    showfields (obj) {
      let newObj = []
      if (obj) {
        Object.keys(obj).forEach((key) => {
          if (this.heardStr.includes(key.split('_')[0])) {
            newObj.push(key)
          }
        })
      }
      // this.$info('最总显示前缀和列为', this.heardStr, newObj)
      this.thObj = this.sortField(newObj)
    },
    // 根据字段后缀得数字对字段进行排序
    sortField (newObj) {
      return newObj.sort((item1, item2) => {
        return (item1.split("_")[2] - 0) - (item2.split("_")[2] - 0)
      })
    },
    // 清空所有条件
    clear () {
      Object.keys(this.$refs.paged.$refs.criteria.model).forEach((key) => {
        this.$refs.paged.$refs.criteria.model[key] = ''
      })
    },
    fliterArr (target, source) {
      let index = -1
      let arr = []
      for (let i = 0; i < target.length; i++) {
        arr = this.intersect(target[i], source)
        if (arr.length > 0) {
          index = i
          // 找到后提前结束for循环
          i = target.length
        }
      }
      console.log('合并前', target, source, index, arr)
      if (index === -1) {
        target.push(source)
      } else {
        target.splice(index, 1)
        target.push(arr)
      }
      return target
    },
    // 比较两个数组，如果有相同部分，返回新数组，否则返回空数组
    intersect (arr1, arr2) {
      for (let i = 0; i < arr1.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i] === arr2[j]) {
            return [arr1[i]]
          }
        }
      }
      return []
    },
    together (depArr) {
      let deped = []
      depArr.forEach((item) => {
        deped = [...deped, ...item]
      })
      return deped
    },
    getParams () {
      let paramlet = paramletGen(this)
      return co(paramlet)
    },
    areachange (val) {
      console.log('区县变更', val)
      this.slices = []
      let slicelet = sliceletGen(this, val)
      return co(slicelet)
    },
    outletsChange (val) {
      this.operators = []
      // console.log('111111111111', val)
      if (val[0] !== '') {
        let operatorlet = operatorletGen(this, val)
        return co(operatorlet)
      } else {
        this.model.f_operator = ''
      }
    }
    // // 按照设计，当选择多个特殊条件时，只显示公用字段部分，不现实显示各自特殊部分
    // // 实现方式，如果目标数组包含资源数组中的一项，及表明有公用字段，则返回目标数组，否则合并两个数组
    // intersect (target, source) {
    //   for (var i = 0; i < source.length; i++) {
    //     if (target.includes(source[i])) {
    //       return target
    //     }
    //   }
    //   return [...target, ...source]
    // }
  },
  watch: {
    'model.state' (val) {
      if (val === '正确' && this.model.rows.length > 0) {
        this.showfields(this.model.rows[0])
      }
    },
    'typename' (val) {
      this.bussiness = val === '业务类型'
      // 清除条件操作
      this.clear()
      // 更改url
      this.model.url = val === '业务类型' ? 'rs/sql/sellQuery' : 'rs/sql/userinfoQuery'
      this.$refs.paged.$refs.criteria.model.startDate = Util.toStandardDateString()
      this.$refs.paged.$refs.criteria.model.endDate = Util.toStandardDateString()
      delete this.model.sums
      this.selfSearch({condition: `1=1 and all_操作时间_23 >= '${Util.toStandardDateString()} 00:00:00' and all_操作时间_23 <= '${Util.toStandardDateString()} 23:59:59'`})
      // this.$refs.paged.$refs.criteria.search()
    },
    'types' (val) {
      if (val.length === 1) {
        // console.log('33333', val)
        if (val[0].type.includes('过户查询')) {
          this.model.url = 'rs/sql/tranQuery'
          this.model.sums = {'all_过户费_11': 0}
        } else if (val[0].type.includes('表具查询')) {
          this.model.url = 'rs/sql/userfilesQuery'
          delete this.model.sums
        } else if (val[0].type.includes('用户查询')) {
          this.model.url = 'rs/sql/userinfoQuery'
          this.model.sums = {'all_结余_11': 0}
        } else if (val[0].type.includes('设备查询')) {
          this.model.url = 'rs/sql/deviceQuery'
          delete this.model.sums
        } else if (val[0].type.includes('冲正查询')) {
          this.model.url = 'rs/sql/correctQuery'
          this.model.sums = {'all_冲正气量_11': 0, 'all_冲正金额_12': 0, 'all_收款_13': 0}
        } else if (val[0].type.includes('补卡查询')) {
          this.model.url = 'rs/sql/fillCardQuery'
          this.model.sums = {'all_卡费_11': 0}
        } else if (val[0].type.includes('补气查询')) {
          this.model.url = 'rs/sql/fillGasQuery'
          this.model.sums = {'all_补气量_11': 0}
        } else if (val[0].type.includes('换表查询')) {
          this.model.url = 'rs/sql/changemeterQuery'
          this.model.sums = {'all_换表费_12': 0}
          console.log('换表合计，，，，', this.model)
        } else if (val[0].type.includes('操作查询')) {
          this.model.url = 'rs/sql/operQuery'
          delete this.model.sums
        } else if (val[0].type.includes('抄表查询')) {
          this.model.url = 'rs/sql/handplanQuery'
          this.model.sums = {'all_用气量_13': 0, 'all_气费_14': 0, 'all_剩余气量_19': 0, 'all_扣减气量_20': 0}
        } else if (val[0].type.includes('其他收费查询')) {
          this.model.url = 'rs/sql/otherQuery'
          this.model.sums = {'all_收款_14': 0}
        } else if (val[0].type.includes('撤销查询')) {
          this.model.url = 'rs/sql/cancelQuery'
          delete this.model.sums
        } else if (val[0].type.includes('收费查询')) {
          this.model.url = 'rs/sql/sellQuery'
          this.model.sums = {'all_气量_11': 0, 'all_应交金额_12': 0, 'all_收款_13': 0}
        }
      }
      // this.model.startDate = Util.toStandardDateString()
      // this.model.endDate = Util.toStandardDateString()
      this.model.search()
    }
  },
  computed: {
    metertypes () {
      return [{label: '全部', value: ''}, ...AppData.getParam('气表类型')]
    },
    usertypes () {
      return [{label: '全部', value: ''}, ...AppData.getParam('用户类型')]
    },
    gasproperties () {
      return [{label: '全部', value: ''}, ...AppData.getParam('用气性质')]
    },
    userstates () {
      return [{label: '全部', value: ''}, ...AppData.getParam('用户状态')]
    },
    adjustables () {
      let arr = []
      AppData.getAdjustable().forEach((item) => {
        let temp = {}
        temp.label = `[${item.value.f_adjustable_id}]-${item.label}`
        temp.value = item.value.f_adjustable_name
        arr.push(temp)
      })
      return [{label: '全部', value: ''}, ...arr]
    },
    meterbrands () {
      let arr = []
      AppData.getGasbrand().forEach((item) => {
        let temp = {}
        temp.label = item.label
        temp.value = item.value.f_meter_brand
        arr.push(temp)
      })
      return [{label: '全部', value: ''}, ...arr]
    },
    states () {
      return [{label: '全部', value: ''}, ...AppData.getParam('状态')]
    },
    getField () {
      // console.log('获取，，，，，，', this.queryDatas, this.types)
      // console.log('获取字段对应的表头', this.queryDatas[this.types[0].type.trim()])
      // console.log('获取字段对应的表头', this.queryDatas['业务公用'])
      // console.log();
      return Object.assign({}, this.typename === '业务类型' ? this.queryDatas['业务公用'] : this.queryDatas['基本公用'], this.queryDatas[this.types[0].type.trim()])
    },
    getCondition () {
      let result = {}
      if (this.$refs[this.types[0].ref].$refs.criteria.condition) {
        result[this.types[0].condition] = this.$refs.paged.$refs.criteria.condition + `and ${this.$refs[this.types[0].ref].$refs.criteria.condition}`
      } else {
        result[this.types[0].condition] = this.$refs.paged.$refs.criteria.condition
      }
      return result
    }
  }
}
</script>
<style lang="less">
  #queryactually label {
    padding-right: 0px;
  }
</style>
